package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//登录过滤
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)  servletRequest;
        String uri = request.getRequestURI();
        HttpServletResponse response=(HttpServletResponse) servletResponse;

         String url=request.getRequestURI();
        System.out.println(url);
        if("/".equals(url)){
            //放行
            filterChain.doFilter(request,response);
        }else {

            if(url.equals("/login")||url.equals("/login.jsp")){
                //登录
                filterChain.doFilter(request,response);
            }else {
                //获取session
                HttpSession session = request.getSession();
                User user = (User) session.getAttribute("user");
                if(user!=null){
                    //登录过 放行
                    filterChain.doFilter(request,response);
                }else {
                    //未登录跳转到登录页面
                    response.sendRedirect("/login.jsp");
                }

            }

        }
     }

    @Override
    public void destroy() {

    }
}
